package com.study.sggds;

import com.alibaba.fastjson.JSON;
import com.study.bean.Account;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

/**
 * @author study
 * @version 1.0
 * @date 2021/4/26 13:53
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo {
    //文档地址|https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high.html

    //API https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-supported-apis.html


    //IndexRequest https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-document-index.html

    @Autowired
    private RestHighLevelClient client;

    @Test
    public void searchData() throws IOException {
        final SearchRequest searchRequest = new SearchRequest();
        //指定索引
        searchRequest.indices("bank");
        //指定DSL，检索条件
        final SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        searchRequest.source(sourceBuilder);
        //1.1 检索条件
        sourceBuilder.query(QueryBuilders.matchQuery("address", "mill"));
        // sourceBuilder.from(0);
        final TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
        sourceBuilder.aggregation(ageAgg);
        //平均薪资
        final AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("balance");//
        sourceBuilder.aggregation(balanceAvg);


        //检索条件
        System.out.println(sourceBuilder);
        //2 执行检索
        final SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //3 分析结果
        System.out.println(searchResponse.toString());
        // JSON.parseObject(searchResponse.toString(),Map.class);
        //3.1 获取所有查到的数据
        final SearchHits hits = searchResponse.getHits();
        final SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            final String sourceAsString = hit.getSourceAsString();
            final Account account = JSON.parseObject(sourceAsString, Account.class);
            System.out.println(account);
        }
        //3.2 分析数据
        final Aggregations aggregations = searchResponse.getAggregations();
        final Terms ageAggRes = aggregations.get("ageAgg");
        for (Terms.Bucket bucket : ageAggRes.getBuckets()) {
            System.out.printf("%s-%s%n", bucket.getKeyAsString(), bucket.getDocCount());
        }

        final Avg balanceAvg1 = aggregations.get("balanceAvg");
        System.out.println("平均薪资:" + balanceAvg1.getValue());


    }


    /**
     * 测试存储数据
     */
    @Test
    public void indexRequest() throws IOException {
        final IndexRequest indexRequest = new IndexRequest("user");
        indexRequest.id("1");
        final User user = new User();
        user.setAge(18);
        user.setUserName("lisi");
        user.setGender("M");
        final String jsonString = JSON.toJSONString(user);
        indexRequest.source(jsonString, XContentType.JSON);
        final IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);//ElasticsearchConfig.COMMON_OPTIONS);
        System.out.println(index);

    }

    @Data
    static class User {
        private String userName;
        private String gender;
        private Integer age;
    }
}
